package com.xuetang.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xuetang.common.ApiResponse;
import com.xuetang.entity.AdminUser;
import com.xuetang.service.AdminUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员认证拦截器
 */
@Component
public class AdminAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 在请求处理之前进行拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 获取当前请求的路径
        String requestURI = request.getRequestURI();

        // 对登录页面和登录请求放行
        if (requestURI.endsWith("/login") || requestURI.endsWith("/user/info") || requestURI.equals("/admin/")
                || requestURI.equals("/admin")) {
            return true;
        }

        // 对预检请求放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 从请求头中获取JWT Token
        String authHeader = request.getHeader(jwtTokenUtil.getHeader());
        if (authHeader != null && authHeader.startsWith(jwtTokenUtil.getTokenPrefix())) {
            String token = authHeader.substring(jwtTokenUtil.getTokenPrefix().length());
            try {
                // 从token中获取用户名
                String username = jwtTokenUtil.getUsernameFromToken(token);
                if (username != null) {
                    // 验证用户是否存在
                    AdminUser adminUser = adminUserService.findByUsername(username);
                    if (adminUser != null) {
                        // 验证通过，放行请求
                        return true;
                    }
                }
            } catch (Exception e) {
                // Token验证失败，返回401未授权
                returnUnauthorized(response, "Token验证失败");
                return false;
            }
        }

        // 未提供有效的Token，返回401未授权
        returnUnauthorized(response, "请先登录");
        return false;
    }

    /**
     * 返回未授权的JSON响应
     */
    private void returnUnauthorized(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");

        ApiResponse apiResponse = ApiResponse.error(401, message);
        response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
    }
}